package io.renren.modules.course.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.oss.cloud.OSSFactory;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysDeptEntity;
import io.renren.modules.sys.entity.SysMenuEntity;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.course.service.*;
import io.renren.modules.course.entity.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-07-03 16:11:00
 */
@RestController
@RequestMapping("sys/coursebody")
public class CourseBodyController extends AbstractController {
    @Autowired
    private CourseBodyService courseBodyService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = courseBodyService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/list1")
    public List list1(@RequestParam Map<String, Object> params){
        List list = courseBodyService.queryList(params);

        return list;
    }
    @RequestMapping("/courseList")
    public List courseList(@RequestParam String courseName){
        List list = courseBodyService.queryListByCourseName(courseName);
        return  list;
    }


    /**
     * 列表
     */
    @RequestMapping("/getCourseTreeList")
    public R getCourseTreeList(){
//查询列表数据
        List<TreeEntity> menuList = courseBodyService.courseBodyService();

        return R.ok().put("menuList", menuList);
    }

    /**
     * 獲取根目錄
     */
    @RequestMapping("/selectGen")
    public R selectGen(Integer id){
        List<TreeEntity> deptList = courseBodyService.getCourseTreeGen(id);

        //添加一级部门
//        if(getUserId() == Constant.SUPER_ADMIN){
//            TreeEntity root = new TreeEntity();
//            root.setId((long) 0);
//            root.setName("根目錄");
//            deptList.add(root);
//        }

        return R.ok().put("deptList", deptList);
    }

    /**
     * 獲取根目錄
     */
    @RequestMapping("/select")
    public R select(Integer id,HttpServletRequest request){
        List<TreeEntity> deptList = courseBodyService.getCourseTree(id);
        HttpSession session = request.getSession();
        session.setAttribute("courseId",id);
        //添加一级部门
//        if(getUserId() == Constant.SUPER_ADMIN){
//            TreeEntity root = new TreeEntity();
//            root.setId((long) 0);
//            root.setName("根目錄");
//            deptList.add(root);
//        }
        System.out.println(session.getAttribute("courseId"));
        return R.ok().put("deptList", deptList);
    }


    /**
     * 上传文件
     */
    /*@RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        excelToEntity(file.getInputStream());
        return R.ok();

    }*/


    /**
     * 上级部门Id(管理员则为0)
     */
    @RequestMapping("/info")
    public R info(){
        long deptId = 0;
        if(getUserId() != Constant.SUPER_ADMIN){
            List<CourseBodyEntity> deptList = courseBodyService.queryList(new HashMap<String, Object>());
            Integer parentId = null;
            for(CourseBodyEntity sysDeptEntity : deptList){
                if(parentId == null){
                    parentId = sysDeptEntity.getParentId();
                    continue;
                }

                if(parentId > sysDeptEntity.getParentId().longValue()){
                    parentId = sysDeptEntity.getParentId();
                }
            }
            deptId = parentId;
        }

        return R.ok().put("deptId", deptId);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){

        CourseBodyEntity courseBody = courseBodyService.selectById(id);

        return R.ok().put("courseBody", courseBody);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CourseBodyEntity courseBody){
        ValidatorUtils.validateEntity(courseBody);
        if(courseBody.getVideoPath()!=null) {
            String videoPath = courseBody.getVideoPath().replace("&amp;", "&");
            courseBody.setVideoPath(videoPath);
            if("".equals(courseBody.getVideoPath())){
                courseBody.setVideoPath(null);
            }
        }
        if(courseBody.getChapterName() != null){
            courseBody.setChapterName(courseBody.getChapterName().replaceAll("&amp;","&"));
        }

        if(courseBody.getDataPath()!= null){
            if(courseBody.getDataPath().contains(".ppt")){
                return R.error(102,"现在仅支持pdf文件哦~");
            }
        }

        if(courseBody.getVideoHdPath() != null){
            if( "".equals(courseBody.getVideoHdPath())){
                courseBody.setVideoHdPath(null);
            }
        }
        if(null == courseBody.getDataPath() || "".equals(courseBody.getDataPath())){
            courseBody.setDataType(null);
        }

        courseBodyService.insert(courseBody);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody CourseBodyEntity courseBody, HttpServletRequest request){
        ValidatorUtils.validateEntity(courseBody);
        if(courseBody.getVideoPath() != null) {
            String videoPath = courseBody.getVideoPath().replace("&amp;", "&");
            courseBody.setVideoPath(videoPath);
            if("".equals(courseBody.getVideoPath())){
                courseBody.setVideoPath(null);
            }
        }
        if(courseBody.getChapterName() != null){
            courseBody.setChapterName(courseBody.getChapterName().replaceAll("&amp;","&"));
        }

        if(courseBody.getDataPath()!= null){
            if(courseBody.getDataPath().contains(".ppt")){
                return R.error(102,"现在仅支持pdf文件哦~");
            }
        }

        if(courseBody.getVideoHdPath() != null){
            if( "".equals(courseBody.getVideoHdPath())){
                courseBody.setVideoHdPath(null);
            }
        }

        if(null == courseBody.getDataPath() ||"".equals(courseBody.getDataPath())){
            courseBody.setDataType(null);
        }
        courseBodyService.updateAllColumnById(courseBody);//全部更新
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody long ids){


        //判断是否有子部门
        List<Long> deptList = courseBodyService.queryDetpIdList(ids);
        if(deptList.size() > 0){
            return R.error("请先删除子课程");
        }
        courseBodyService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    @RequestMapping("getChapterIdAndSectionId")
    private R getSectionId(@RequestBody Map treeNode,HttpServletRequest request) {
/*     int sectionId = Integer.parseInt(treeNode.toString());
        System.out.println(sectionId);*/
     //request.getSession().setAttribute("sectionId",sectionId);
        int id = Integer.valueOf(treeNode.get("id").toString());
        int parentId= Integer.valueOf(treeNode.get("parentId").toString());
        request.getSession().setAttribute("courseBodyId",id);
        request.getSession().setAttribute("chapterId",parentId);
        request.getSession().setAttribute("type",treeNode.get("type"));
        //if()
         return R.ok();
    }



    @RequestMapping(value="/changeCourseToSmall",method = RequestMethod.POST)
    @ResponseBody
    //@RequiresPermissions("course:coursetest:uploadTest")
    public R changeCourseToSmall(@RequestParam(value="file",required = false) MultipartFile file, HttpServletRequest request) {

        if(file == null){
            return R.error(101,"文件为空");
        }
Long teacherId = getUserId();

        return courseBodyService.changeCourseToSmall(file,teacherId);
    }
}
